package controller

import (
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"net/http"
	"study_abroad_system_back_end/common"
	"study_abroad_system_back_end/common/StatusCode"
	"study_abroad_system_back_end/dao"
	"study_abroad_system_back_end/models"
	"study_abroad_system_back_end/response"
	"study_abroad_system_back_end/serializer"
	"time"
)

func Register(ctx *gin.Context) {
	username := ctx.PostForm("username")
	password := ctx.PostForm("password")
	telephone := ctx.PostForm("telephone")
	addtime := time.Now().UTC()

	code := StatusCode.SUCCESS

	if dao.IsUsernameExist(telephone) {
		code = StatusCode.ERROR_EXIST_USER
		response.Response(ctx, http.StatusOK, code, nil, StatusCode.GetMsg(code))
		return
	}

	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		code = StatusCode.ERROR_FAIL_ENCRYPTION
		response.Response(ctx, http.StatusOK, code, nil, StatusCode.GetMsg(code))
		return
	}

	user := models.User{
		Username:  username,
		Password:  string(hashedPassword),
		Telephone: telephone,
		Addtime:   addtime,
		Logintime: addtime,
	}
	err = dao.DB.Create(&user).Error
	if err != nil {
		panic(err)
		return
	}
	response.Response(ctx, http.StatusOK, code, nil, StatusCode.GetMsg(code))
}

func Login(ctx *gin.Context) {
	DB := dao.GetDB()
	telephone := ctx.PostForm("telephone")
	password := ctx.PostForm("password")
	logintime := time.Now().UTC()

	var user models.User
	code := StatusCode.SUCCESS
	//查找用户
	DB.Where("telephone=?", telephone).First(&user)
	if user.ID == 0 {
		code = StatusCode.ERROR_NOT_EXIST_USER
		response.Response(ctx, http.StatusOK, code, nil, StatusCode.GetMsg(code))
		return
	}

	//判断密码是否正确
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		code = StatusCode.ERROR_NOT_COMPARE
		response.Response(ctx, http.StatusOK, code, nil, StatusCode.GetMsg(code))
		return
	}

	//发token
	token, err := common.GenerateToken(telephone, password, 1)
	if err != nil {
		code = StatusCode.ERROR_AUTH_TOKEN
		response.Response(ctx, http.StatusOK, code, nil, StatusCode.GetMsg(code))
		return
	}

	DB.Model(&user).Where("telephone=?", telephone).Update("Logintime", logintime)

	response.Response(ctx, http.StatusOK, code, gin.H{"token": token, "user": serializer.BuildUser(user)}, StatusCode.GetMsg(code))
}
